﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using EvaluationSystem.DAO;
using System.Data;
using System.Text;
using Ext.Net;
using EvaluationSystem.Exceptions;

namespace EvaluationSystem.ConfigurationPages
{
    public partial class StaffEditPage1 : System.Web.UI.Page
    {
        StaffManager staffManager = null;
        protected string UserId
        {
            get
            {
                return Request.QueryString[StaffConstants.UserId];
            }
        }

        protected string Role
        {
            get
            {
                return Request.QueryString[StaffConstants.RorleName];
            }
        }

        protected string Groups
        {
            get
            {
                return Request.QueryString[StaffConstants.Groups];
            }
        }

        protected void Page_Load(object sender, EventArgs e)
        {
            if (!Utility.IsLogin(this.Page))
            {
#if !DEBUG
                Response.Redirect("../Default.aspx");
#endif
            }
            if (String.IsNullOrEmpty(UserId) || String.IsNullOrEmpty(Role) || String.IsNullOrEmpty(Groups))
            {
                throw new ArgumentNullException();
            }
            staffManager = new StaffManager();
            if (!X.IsAjaxRequest)
            {
                InitRoles();
                InitGroups();
            }
            
        }

        private void InitGroups()
        {
            DataTable dt = staffManager.GetGroups();
            DataTable dtSelectedUser = staffManager.GetUserById(UserId);
            //string groups = dtSelectedUser.Rows[0]["Groups"] as string;
            txtUsername.Text = dtSelectedUser.Rows[0]["UserName"] as string;
            string[] selectedGroups = null;

            selectedGroups = Groups.Split(Constants.SplitKey.ToCharArray());
            Ext.Net.TreeNode root = new Ext.Net.TreeNode();
            foreach (DataRow row in dt.Rows)
            {
                Ext.Net.TreeNode node = new Ext.Net.TreeNode(row[0].ToString(), row[1] as string, Icon.ArrowJoin);
                node.Checked = selectedGroups == null || !selectedGroups.Contains(node.Text)? ThreeStateBool.False: ThreeStateBool.True;
                if (node.Checked == ThreeStateBool.True)
                {
                    InitGroupDisplayValue(row[1] as string);
                }
                node.Leaf = true;
                root.Nodes.Add(node);
            }
            tpGroup.Root.Add(root);
        }

        private void InitGroupDisplayValue(string value)
        {
            string theValue = ddfGroup.Text;
            if (ddfGroup.Text.Length > 0)
            {
                theValue += Constants.SplitKey;
            }
            theValue += value;
            ddfGroup.Text = theValue;
        }

        private void InitRoles()
        {
            StringBuilder sbToolTip = new StringBuilder();
            DataTable dt = staffManager.GetRoles();

            foreach (DataRow row in dt.Rows)
            {
                Ext.Net.ListItem item = new Ext.Net.ListItem(row[1] as string);
                item.Value = row[0].ToString();
                cbbRole.Items.Add(item);
                sbToolTip.Append(String.Format("<table><tr><td width=70>{0}</td><td width=200>{1}</td></tr></table>", row[1] as string, row[2] as string));
                if (row[1].Equals(Role))
                {
                    cbbRole.SelectedIndex = cbbRole.Items.Count - 1;
                }
            }

            tooltipForRole.Html = sbToolTip.ToString();
        }

        protected void btnSave_Click(object sender, DirectEventArgs e)
        {
            try
            {
                bool isSuccess = staffManager.UpdateStaffById(UserId, txtUsername.Text.Trim(), String.IsNullOrEmpty(txtPassword.Text.Trim()) ? null : Utility.MD5(txtPassword.Text.Trim()), ddfGroup.Text, cbbRole.Value.ToString());
                if (isSuccess)
                {
                    X.MessageBox.Alert(Constants.Noticfy, "修改用户成功.").Show();

                }
                else
                {
                    X.MessageBox.Alert(Constants.Noticfy, "保存出错，请重新尝试或联系开发人员.").Show();
                }
            }
            catch (InvalidUserException ex)
            {
                X.MessageBox.Alert(Constants.Noticfy, ex.Message).Show();
                txtUsername.Focus();
                txtUsername.SelectText(0);
            }
        }
    }
}